package cc.jinglupeng.wechat.api;

import org.apache.log4j.Logger;

import cc.jinglupeng.wechat.bean.Status;
import cc.jinglupeng.wechat.bean.menu.Menu;
import cc.jinglupeng.wechat.bean.menu.MenuResp;
import cc.jinglupeng.wechat.util.WxHttpUtils;

/**
 * 菜单API
 * 
 * @author jinglupeng.cc
 */
public final class MenuAPI {

	private static Logger logger = Logger.getLogger(MenuAPI.class);

	private final static String GET_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	private final static String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	private final static String CREATE_MENU_URL = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	/**
	 * 自定义菜单查询接口
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @return
	 */
	public static Menu getMenu(String appId) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("自定义菜单查询失败, 获取AccessToken失败!");
			return null;
		}
		String url = GET_MENU_URL.replace("ACCESS_TOKEN", token);
		MenuResp menu = WxHttpUtils.get(url, MenuResp.class);
		if (menu.isSuccess()) {
			return menu.getMenu();
		}
		return null;
	}

	/**
	 * 删除菜单
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @return
	 */
	public static Boolean deleteMenu(String appId) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("删除菜单失败, 获取AccessToken失败!");
			return false;
		}
		String url = DELETE_MENU_URL.replace("ACCESS_TOKEN", token);
		Status status = WxHttpUtils.get(url, Status.class);
		return status.isSuccess();
	}

	/**
	 * 自定义菜单创建
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param menu
	 *            -JSON形式的菜单
	 * @return
	 */
	public static Boolean createMenu(String appId, String menu) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("自定义菜单创建失败，获取AccessToken失败!");
			return false;
		}
		String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
		Status status = WxHttpUtils.post(url, menu, Status.class);
		return status.isSuccess();
	}

}
